package com.mygame.gateway.server;

import com.mygame.common.codec.DataCodecKit;
import com.mygame.common.protobuf.ExternalMessage;
import jakarta.annotation.PostConstruct;
//import org.apache.kafka.clients.consumer.ConsumerRecord;
import com.mygame.common.natsConfig.Subscribe;
import io.nats.streaming.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import io.netty.channel.Channel;

/**
 * 接收业务服务返回的消息，并发送到客户端
 */
@Service
public class ReceiveNatsResponseService {
    private Logger logger = LoggerFactory.getLogger(ReceiveNatsResponseService.class);
    @Autowired
    private GatewayServerConfig gatewayServerConfig;
    @Autowired
    private ChannelService channelService;

    @PostConstruct
    public void init() {
        logger.info("监听消息接收业务消息topic:{}", gatewayServerConfig.getGatewayGameMessageTopic());
    }

    /**
     * 监听业务消息,返回给客户端
     */
    @Subscribe(value = "gateway-game-message-topic", durableName = "bar", queue = "queue")
    public void receiverGameMsg(Message message) {
        ExternalMessage externalMessage = DataCodecKit.decode(message.getData(), ExternalMessage.class);
        Long playerId = externalMessage.getPlayerId();//从包头中获取这个消息包归属的playerId
        Channel channel = channelService.getChannel(playerId);//根据playerId找到这个客户端的连接Channel
        if (channel != null) {
            channel.writeAndFlush(externalMessage);//给客户端返回消息
        }
    }
}
